import backend
#
from etoffiutils2.list_ import head, tail
from etoffiutils2.pkg import true, false
import time
#, sys
#~ import os
#

class Client:
	def __init__(self):
		self._quitNow = false
		self.lines = []
		self.text = ''
		self.target_ = None
		self.mt=backend.initializeMsgTarget("AwxMessageClientDemo", self)
	def run(self):
		print 'start running'
		#~ m = backend.GetMessage()
		#~ if not m:
			#~ self._quitNow = True
		while not self._quitNow:
			time.sleep(1)
			#~ self.handle (m)
			#~ m = backend.GetMessage()
			#~ if not m:
				#~ self._quitNow = True
	def handle(self, msg):
		print 100,msg
		if msg.main == 'respond qualfiy':
			self.lines += [msg["text"]]
		elif msg.main == 'expose keyup':
			aa = int(msg['key'])
			if aa == 13:
				self.handle('expose lineadded')
				self.text = ''
			else:
				self.text += chr(aa)
		elif msg.main == 'expose lineadded':
			self.addLine(msg)
	
	def addLine (self, m):
		#~ print 39,m
		assert m.main == "expose lineadded"
		assert self.target_ != None
		
		print 46,self.lines
		r = backend.Message(self.mt, self.target_, "expose qualify")
		#~ r.add ("text", textEntry1.Text) # property -or- getText()
		#
		#
		r.add("text", m['text']) 
		r.send()
	
	def init(self, args):
		self.target_ = self.mt.targetFor ("AwxMessageServerDemo")
		print 49,self.target_
		self.postInit()
	def postInit(self):
		import threading
		gt = threading.Thread(target=self._postInit)
		gt.setDaemon(1)
		gt.start()
	def _postInit(self):
		n=0
		try:
			try:
				while n<15:
					for each in range(10):
						Y=abs(10-each)
						#~ print '\a'
						print 'bell ** yy',Y
						time.sleep(Y)
						
						msg = backend.Message (0, self, "expose lineadded")
						msg.add ("text", `each`)
						#~ msg.send()
						self.handle(msg)
						#~ self.addLine(msg)
					print 66,n
					n=n+1
			except Exception,e:
				import traceback
				traceback.print_exc()
				print '!! 69',e
		finally:
			print 'gui bye'
			self._quitNow=true
			#~ raise SystemExit

if __name__=='__main__':
	
	c = Client()
	c.init([])
	c.run()
	print 'client out'
